package com.ruoyi.detection.controller;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.Threads;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.detection.domain.DetectionLog;
import com.ruoyi.detection.service.ModelService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.topInsectImg.domain.WebFrontEnd;
import com.ruoyi.utils.ImgDrawCircleTool;
import com.ruoyi.utils.ParseArray;
import com.ruoyi.utils.ParseString;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * 智能检测与识别模型
 *
 * @author Mr-Le
 */
@Api("智能检测模型")
@Slf4j
@RestController
@RequestMapping("/detection")
public class ModelController {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ModelService modelService;

    /**
     * 存储文件的路径
     */
    @Value("${ruoyi.profile}")
    private String profile;

    /**
     * 模型检测图像处理路径
     */
    @Value("${ruoyi.detectionUrl}")
    private String detectionUrl;

    @ApiOperation("调用模型检测")
    @PostMapping("/model")
    public AjaxResult model(@RequestParam("imageName") MultipartFile file) throws IOException {
        if (!file.isEmpty()) {
            // upload() : 返回的就是文件路径
            String images = FileUploadUtils.upload(RuoYiConfig.getDetectionPath(), file);
            String detectionImages = StringUtils.substringAfter(images, "profile");
            WebFrontEnd frontEnd = new WebFrontEnd();
            frontEnd.setThumUrl(images.replace("original", "thum")).setImgTime(ParseString.string2Date(file.getOriginalFilename()))
                    .setImageName(file.getOriginalFilename());
            modelService.updateWebFrontEnd(frontEnd);
            /* 解析识别结果构造实例存入数据库并返回, 检测不需要list集合，识别有多个可能，需要集合装载，其他的不需要 */
            List<DetectionLog> detectionLogList = new ArrayList<>();
            DetectionLog detectionLog = null;
            ImgDrawCircleTool tool = new ImgDrawCircleTool();

            try {
                // 图片发送到Django进行识别
                ResponseEntity<String> responseEntity = Threads.detectionRequest(profile + detectionImages, detectionUrl);
                log.info("responseEntity------->" + responseEntity.getBody());
                // json格式的数据转换成数组格式
                detectionLogList = JSON.parseArray(responseEntity.getBody(), DetectionLog.class);
                log.info(detectionLogList.toString());
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
            if (StringUtils.isNotNull(detectionLogList)) {
                for (DetectionLog detection : detectionLogList) {
                    if (StringUtils.isNotNull(detection)) {
//                    detection.setStrCorner(ParseArray.parseArrayList(detection.getCorner()));
                        detection.setImagePath(images).setOriginalFileName(file.getOriginalFilename());

                        /*画框之后的结果图 resUrl  缩略图 已添加 */
                        List<String> tagList = JSON.parseArray(detection.getTag(), String.class);
                        String resultPath = tool.doDrawRectangle(detection.getCorner(), tagList, profile + detectionImages).replace(profile, Constants.RESOURCE_PREFIX);

                        detection.setTag(ParseString.getTagNum(detection.getTag()));
                        frontEnd.setTag(detection.getTag()).setStrCorner(detection.getStrCorner()).setImageName(detection.getOriginalFileName()).setResUrl(resultPath);

                        System.out.println(frontEnd.toString());
                        modelService.updateWebFrontEnd(frontEnd);
                        modelService.insertDetectionLog(detection);
                    }
                }
                return AjaxResult.success(detectionLogList);
            }
            return AjaxResult.success("再试一次");
        }
        return AjaxResult.error("上传图片异常");
    }

    /**
     * 设置检测模型实体类参数
     * @param detectionLog  检测模型实体类
     * @param imagePath 原图上传路径
     * @param originalFileName  源文件名称
     * @return 对象
     */
//    private DetectionLog setDetectionLogPram(DetectionLog detectionLog, String imagePath, String originalFileName){
//        detectionLog.setImagePath(imagePath)
//                    .setOriginalFileName(originalFileName);
//        return detectionLog;
//    }

    /**
     * 添加Result标签
     */
    private static String addResult(String srcPath) {
        String res = "";
        if (StringUtils.isNotNull(srcPath)) {
            String[] str = new String[2];
            /* \\. 转义字符，相当于 . ,分隔出.前后的内容 */
            str = srcPath.split("\\.");
            res = str[0] + "__Result." + str[1];
        }
        return res;
    }
}
